﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Rabbit.API.Application.Command.Goods;

namespace Rabbit.API.Application.Handler.Goods
{
    /// <summary>
    /// 商品信息修改 实现
    /// </summary>
    public class GoodsUpdateHandler:IRequestHandler<GoodsUpdateCommand,APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly ILogger<GoodsAddHandler> log;
        private readonly IMapper mapper;

        public GoodsUpdateHandler(IRepository<GoodsModel> goodsway, ILogger<GoodsAddHandler> log, IMapper mapper)
        {
            this.goodsway = goodsway;
            this.log = log;
            this.mapper = mapper;
        }
        /// <summary>
        /// 商品信息修改
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> Handle(GoodsUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            try
            {
                var goods =await goodsway.GetValue(request.Id);
                if(goods!=null)
                {
                    goods.GoodsName = request.GoodsName;
                    goods.CreateBatch = request.CreateBatch;
                    goods.CreateCode = request.CreateCode;
                    goods.ExpireTime = request.ExpireTime;
                    goods.Covers = request.Covers;
                    goods.Tests = request.Tests;
                    goods.CreateCompany = request.CreateCompany;

                    var result = await goodsway.Updateway(goods);
                    if(result>0)
                    {
                        log.LogInformation($"商品信息修改成功");
                        res.Message = "商品信息修改成功";
                        res.Num = StateCode.OK;
                        res.Data = result;
                        
                    }
                    else
                    {
                        res.Message = "商品信息修改失败";
                        res.Num = StateCode.Fail;
                    }
                }
                else
                {
                    res.Message = "不存在要修改的信息";
                    res.Num = StateCode.Fail;
                }
                return res;
            }
            catch (Exception ex)
            {
                log.LogError($"发生异常{ex.Message}");
                throw;
            }
        }
    }
}
